package com.diors.commons.utils;

import java.io.File;
import java.io.FileOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * xml工具类
 * @author 	欧阳
 * @date	2013-6-5
 */
public class XmlObjectUtil 
{

    public XmlObjectUtil(){}

    public static Object XmlToJavaBean (String fileName, Class<? extends Object> clazz) throws Exception
    {
        JAXBContext jc = JAXBContext.newInstance(new Class[] {clazz});
        Unmarshaller un = jc.createUnmarshaller();
        Object t = un.unmarshal(new File(fileName));
        return t;
    }

    public static Object XmlToJavaBean (File file, Class<? extends Object> clazz) throws Exception
    {
        JAXBContext jc = JAXBContext.newInstance(new Class[] {clazz});
        Unmarshaller un = jc.createUnmarshaller();
        Object t = un.unmarshal(file);
        return t;
    }

    public static void JavaBeanToXml (String file, Object obj) throws Exception
    {
        JAXBContext jc = JAXBContext.newInstance(new Class[] {obj.getClass()});
        Marshaller ms = jc.createMarshaller();
        ms.setProperty("jaxb.formatted.output", Boolean.TRUE);
        FileOutputStream stream = new FileOutputStream(file);
        ms.marshal(obj, stream);
    }
}

